using SqlSugar;
using IM.Easy.Core.Services;
using IM.Easy.Core.Utils;
using IM.Easy.Infrastructure.Query;
using IM.Easy.Core.Extensions;
using IM.Easy.Entity.System;
using IM.Easy.SystemServices.Dtos;
using IM.Easy.SystemServices.IServices;

namespace IM.Easy.SystemServices.Services
{
    public class UserRoleService : AppServices, IUserRoleService
    {

        public UserRoleService(ISqlSugarClient db) : base(db)
        {

        }


        public SysUserRole GetById(long id)
        {
            // TODO: 添加获取逻辑
            return Db.Queryable<SysUserRole>().InSingle(id);
        }

        public PageResponse<SysUserRole> GetPageList(UserRoleQueryDto query)
        {
            var queryable = Db.Queryable<SysUserRole>();
            var exp = Expressionable.Create<SysUserRole>();
            exp = exp
;
            var page = queryable
                 .Where(exp.ToExpression())
                 .ToPageList<SysUserRole, SysUserRole>(query);
            return page;
        }

        public bool Delete(params long[] UserId)
        {
            // TODO: 添加删除逻辑
            return Db.Deleteable<SysUserRole>(UserId).ExecuteCommandHasChange();
        }

        /// <summary>
        /// 获取用户角色
        /// </summary>
        /// <param name="userId"></param>
        public List<SysRole> GetUserRoles(long userId)
        {
            var user = Db.Queryable<SysUser>()
                 .Includes(s => s.Roles.Where(r => r.IsActive).ToList())
                 .InSingle(userId);
            return user.Roles;
        }

        /// <summary>
        /// 保存用户角色
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool SaveUserRoles(UserRoleDto dto)
        {
            var user = Db.Queryable<SysUser>().InSingle(dto.UserId);
            user.Roles = dto.RoleId.Select(roleId => new SysRole { Id = roleId }).ToList();

            var result = Db.UpdateNav(user)
                           .Include(x => x.Roles)
                           .ExecuteCommand();
            return result;
        }
    }
}
